// 从 storage 中加载密码并展示
document.addEventListener('DOMContentLoaded', function () {
  const passwordList = document.getElementById('password-list');
  const addForm = document.getElementById('add-form');
  const clearAllBtn = document.getElementById('clear-all');
  const toggleAddBtn = document.getElementById('toggle-add-btn');
  const urlInput = document.getElementById('url');
  const usernameInput = document.getElementById('username');
  const passwordInput = document.getElementById('password');

  // 切换添加表单位置
  function toggleAddForm() {
    if (addForm.style.display === 'none' || !addForm.style.display) {
      addForm.style.display = 'flex';
      toggleAddBtn.textContent = '−';
    } else {
      addForm.style.display = 'none';
      toggleAddBtn.textContent = '+';
    }
  }


  // 加载密码
  function loadPasswords() {
    chrome.storage.local.get({ passwords: [] }, function (result) {
      const passwords = result.passwords;
      passwordList.innerHTML = '';

      if (passwords.length === 0) {
        const emptyItem = document.createElement('li');
        emptyItem.textContent = '暂无保存的密码';
        passwordList.appendChild(emptyItem);
        return;
      }

      passwords.forEach((entry, index) => {
        const item = document.createElement('li');
        item.className = 'password-item';
        item.style.cursor = 'pointer';

        const infoDiv = document.createElement('div');
        infoDiv.className = 'password-info';
        infoDiv.innerHTML = `<strong>域名:</strong> ${entry.url}<br><strong>用户名:</strong> ${entry.username}`;

        const buttonGroup = document.createElement('div');
        buttonGroup.className = 'button-group';

        // 删除按钮（简化为图标风格）
        const deleteBtn = document.createElement('button');
        deleteBtn.textContent = '🗑️';
        deleteBtn.title = '删除';
        deleteBtn.onclick = function (e) {
          e.stopPropagation(); // 阻止点击条目事件
          passwords.splice(index, 1);
          chrome.storage.local.set({ passwords: passwords }, function () {
            loadPasswords();
          });
        };

        buttonGroup.appendChild(deleteBtn);

        // 点击整条记录填充
        item.addEventListener('click', function () {
          // 发送填充消息
          chrome.runtime.sendMessage({ action: 'fillCredentials', entry: entry });

          // 触发波纹动画（通过 CSS 类控制）
          const ripple = document.createElement('span');
          ripple.className = 'ripple';
          ripple.style.left = '50%';
          ripple.style.top = '50%';
          item.appendChild(ripple);
          
          // 使用 setTimeout 替代监听器来移除动画元素
          setTimeout(() => {
            if (ripple && ripple.parentNode === item) {
              item.removeChild(ripple);
            }
          }, 600);
        });

        // 双击进入编辑模式
        item.addEventListener('dblclick', function () {
          urlInput.value = entry.url;
          usernameInput.value = entry.username;
          passwordInput.value = entry.password;
          // 显示添加表单
          if (addForm.style.display === 'none') {
            toggleAddForm();
          }
        });


        // 鼠标进入时显示按钮
        item.addEventListener('mouseenter', () => {
          buttonGroup.style.opacity = '1';
          buttonGroup.style.visibility = 'visible';
        });

        // 鼠标离开时隐藏按钮
        item.addEventListener('mouseleave', () => {
          buttonGroup.style.opacity = '0';
          buttonGroup.style.visibility = 'hidden';
        });

        item.appendChild(infoDiv);
        item.appendChild(buttonGroup);
        passwordList.appendChild(item);
      });

      // 点击页面其他区域关闭菜单
    });
  }

  // 手动添加密码
  addForm.addEventListener('submit', function (e) {
    e.preventDefault();
    const url = document.getElementById('url').value.trim();
    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value.trim();

    if (!url || !username || !password) {
      alert('请填写所有字段');
      return;
    }

    chrome.storage.local.get({ passwords: [] }, function (result) {
      let passwords = result.passwords;
      const entryIndex = passwords.findIndex(entry => entry.url === url && entry.username === username);

      if (entryIndex === -1) {
        // 新增记录
        passwords.push({ url, username, password });
        console.log('新增账号密码记录:', { url, username, password });
      } else {
        // 更新已有记录的密码
        passwords[entryIndex].password = password;
        console.log('更新已有账号密码记录:', passwords[entryIndex]);
      }

      // 持久化存储并刷新界面
      chrome.storage.local.set({ passwords: passwords }, function () {
        loadPasswords();
        addForm.reset();
      });
    });
  });

  // 清除全部密码
  clearAllBtn.addEventListener('click', function () {
    if (confirm('确定要清除所有保存的密码吗？')) {
      chrome.storage.local.set({ passwords: [] }, function () {
        loadPasswords();
      });
    }
  });

  // 默认隐藏添加表单
  if (addForm) {
    addForm.style.display = 'none';
  }

  // 绑定切换按钮点击事件
  if (toggleAddBtn) {
    toggleAddBtn.addEventListener('click', toggleAddForm);
  }

  loadPasswords();

  // 消息监听器
  chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.action === 'fillCredentials') {
      fillCredentials(request.entry);
    } else if (request.action === "deletePassword") {
      // 处理删除密码的逻辑
      const selectedEntry = passwords.find(entry => entry.url === window.location.origin);
      if (selectedEntry) {
        const confirmDelete = confirm(`确定要删除以下账户吗？\n${selectedEntry.url}\n用户名: ${selectedEntry.username}`);
        if (confirmDelete) {
          const index = passwords.indexOf(selectedEntry);
          passwords.splice(index, 1);
          chrome.storage.local.set({ passwords: passwords }, function () {
            loadPasswords();
          });
        }
      }
    }
  });
});

// 填充凭证函数
function fillCredentials(entry) {
  // 发送消息给背景脚本，由其委托内容脚本执行填充
  chrome.runtime.sendMessage({
    action: 'fillCredentials',
    entry: entry
  }, function (response) {
    if (chrome.runtime.lastError) {
      console.error('发送填充消息失败:', chrome.runtime.lastError);
    }
  });
}

// 捕获密码函数
function capturePasswords() {
  const usernameInput = document.querySelector('input[type="text"], input[type="email"]');
  const passwordInput = document.querySelector('input[type="password"]');

  if (usernameInput && passwordInput) {
    const entry = {
      url: window.location.origin,
      username: usernameInput.value,
      password: passwordInput.value
    };

    chrome.storage.local.get({ passwords: [] }, function (result) {
      let passwords = result.passwords;
      const entryIndex = passwords.findIndex(e => e.url === entry.url && e.username === entry.username);

      if (entryIndex === -1) {
        // 新增记录
        passwords.push(entry);
        console.log('新增账号密码记录:', entry);
      } else {
        // 更新已有记录的密码
        passwords[entryIndex].password = entry.password;
        console.log('更新已有账号密码记录:', passwords[entryIndex]);
      }

      // 持久化存储
      chrome.storage.local.set({ passwords: passwords }, function () {
        console.log('密码已保存');
      });
    });
  } else {
    console.warn('未找到用户名或密码输入框');
  }
}

// 生成随机手机号
function generateRandomPhone() {
    const prefix = ['13', '15', '18', '17', '19'];
    let phone = prefix[Math.floor(Math.random() * prefix.length)];
    for (let i = 0; i < 8; i++) {
        phone += Math.floor(Math.random() * 10);
    }
    return phone;
}

// 生成随机邮箱
function generateRandomEmail() {
    const domains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'qq.com', '163.com'];
    const usernameLength = Math.floor(Math.random() * 8) + 5;
    let username = '';
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    
    for (let i = 0; i < usernameLength; i++) {
        username += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    
    return username + '@' + domains[Math.floor(Math.random() * domains.length)];
}

// 生成随机文本
function generateRandomText(length = 8) {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let result = '';
    
    for (let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    
    return result;
}

// 获取表单信息并填充
async function fillForm() {
    // 获取当前标签页
    const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
    
    // 向content.js发送消息，请求获取表单信息
    chrome.scripting.executeScript({
        target: {tabId: tab.id},
        func: getFormInfo
    });
}

// 接收表单信息并处理
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    if (msg.type === 'FORM_INFO') {
        const formFields = msg.data;
        
        // 创建字段映射
        const fieldMap = {};
        
        formFields.forEach(field => {
            if (field.type === 'text' || field.type === 'email' || field.type === 'tel' || field.type === 'password') {
                if (field.name && field.name.toLowerCase().includes('phone')) {
                    fieldMap[field.name] = generateRandomPhone();
                } else if (field.name && field.name.toLowerCase().includes('email')) {
                    fieldMap[field.name] = generateRandomEmail();
                } else if (field.name) {
                    fieldMap[field.name] = generateRandomText();
                }
            }
        });
        
        // 对于密码字段，使用对应的用户名字段值作为密码
        formFields.forEach(field => {
            if (field.type === 'password' && field.name) {
                // 寻找关联的用户名字段
                const usernameField = formFields.find(f => 
                    (f.type === 'text' || f.type === 'email') && 
                    f.name && 
                    (f.name.toLowerCase().includes('user') || f.name.toLowerCase().includes('account'))
                );
                
                if (usernameField && usernameField.name && fieldMap[usernameField.name]) {
                    fieldMap[field.name] = fieldMap[usernameField.name];
                }
            }
        });
        
        // 发送填充表单的消息
        const [tab] = chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
            chrome.scripting.executeScript({
                target: {tabId: tabs[0].id},
                func: fillFormFields,
                args: [fieldMap]
            });
        });
    }
});

// 添加按钮点击事件监听器
document.getElementById('fillFormBtn').addEventListener('click', () => {
    fillForm();
});
